import { Controller, Get, Post, Body, Patch, Param, Delete, Query, Inject } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { EmailService } from 'src/email/email.service';
import { RedisService } from 'src/redis/redis.service';
import { LoginUserDto } from './dto/login-user.dto';
import { RequireLogin, UserInfo } from 'src/decorator/custom.decorator';

@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}
    @Inject(RedisService)
    private redisService: RedisService;
    @Inject(EmailService)
    private emailService: EmailService;
    

    // 注册验证码 
    @Get('captcha')
    async captcha(@Query("email") email:string){
        const code = Math.random().toString().slice(2,8);
        await this.redisService.set(`captcha_${email}`, code , 5 * 60)
        // 发送邮件
        await this.emailService.sendMail({
            to:email,
            subject:"聊天室系统验证码",
            html:`<p> 验证码是${code} , 5分钟内有效 </p>`
        })
        return "发送验证码成功"
    }

    // 注册
    @Post('register')
    async register(@Body() registerUser:CreateUserDto ){
        const user = await this.userService.create(registerUser)
        await this.redisService.del(`captcha_${registerUser.email}`)// 删除 redis缓存的数据
        return user
    }

    // 登录
    @Post('login')
    async login(@Body() loginUser: LoginUserDto ){
        return await this.userService.login(loginUser)
    }


    // 获取好友列表
    @Get('friendship')
    @RequireLogin()
    async friendship(@UserInfo("userId") userId:number , @Query('name') name:string){
        return await this.userService.friendship(userId , name)
    }
    
}
